package com.lifuixng.picturebackend.aop;

import com.lifuixng.picturebackend.annotation.AuthCheck;
import com.lifuixng.picturebackend.exception.BusinessException;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.model.enums.UserRoleEnum;
import com.lifuixng.picturebackend.model.vo.user.UserLoginVO;
import com.lifuixng.picturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author Mr.LiFuXing
 * @Date 2024/12/14 18:34
 * @Title AuthInterceptor
 * @Package com.lifuixng.picturebackend.aop
 */

/**
 * 权限验证的AOP
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {

        // 使用该注解，用户必须要登陆
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取到当前登录的用户信息，loginUser肯定不为空，在getLoginUser方法中，为空就抛出异常了，也就意味着使用了该注解，前提是用户已经登录了
        UserLoginVO loginUser = userService.getLoginUser(request);

        // 获取注解的参数(角色)，进行权限判断
        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 注解没有参数，就是不需要权限
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 注解有参数，需要权限
        // 获取用户具有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 如果当前用户没有权限（权限为空），抛出异常
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 当前登录的用户有权限
        // 要求必须是管理员权限，且用户也有管理员权限
        if (!UserRoleEnum.ADMIN.equals(userRoleEnum) && UserRoleEnum.ADMIN.equals(mustRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 通过权限验证，放行
        return joinPoint.proceed();


    }
}
